import { useNavigate } from 'react-router-dom'
import '../assets/css/Msg.css'
import { useState } from "react"
import store from '../redux/store'
import { saveMsgAvatar, removeChat } from '../redux/action'

function Msg() {
    const [arrList, setList] = useState([])
    let arr = []
    const navigate = useNavigate()
    Object.keys(sessionStorage).forEach(x => {
        let o = {}
        o.name = x
        o.value = sessionStorage.getItem(x)
        arr.push(o)
    })
    if (arrList.length == 0) {
        setList(arr)
    }
    return (
        <div>
            {
                arrList.map((item, index) => (
                    <div className="msgBox" onClick={() => {
                        store.dispatch(removeChat())
                        store.dispatch(saveMsgAvatar(JSON.parse(item.value)[0].avatar))
                        navigate('/main/Chat', { state: { name: item.name } })
                    }}>
                        <img className="msgAvatar" src={JSON.parse(item.value)[0].avatar} width="10%" alt="" />
                        <div className="wordBox">
                            <p className="msgName">{item.name}</p>
                            <p className="msgCon">{JSON.parse(item.value)[JSON.parse(item.value).length - 1].msg}</p>
                        </div>
                    </div>
                ))
            }
        </div>
    )
}

export default Msg